<?php
defined('BASEPATH') or exit('No direct script access allowed!');

class MProject extends CI_Model {
  function __construct() {
    parent::__construct();
    $this->load->library('elfSecurity');
    $this->load->database();
  }

  function add($name, $summary, $tagColor, $createdBy, $group) {
    do {
      $hash = $this->elfsecurity->randStr(15);
      $result = $this->db->where('hash', $hash)->get('project')->row();
    } while (!empty($result));
    $this->db->insert('project', array(
      'hash' => $hash,
      'name' => $name,
      'summary' => $summary,
      'tagColor' => $tagColor,
      'createdTime' => date('Y-m-d H:i:s'),
      'createdBy' => $createdBy,
      'group' => $group
    ));
    // add root task
    $this->load->model('MTask', 'mtask');
    $result = $this->db->where('hash', $hash)->get('project')->row();
    $this->mtask->add($hash, '-1', 'root', '', $createdBy, 'the root task', 'root');
    return $result;
  }

  function get($hash, $group) {
    if($group != 'admin') {
      $this->db->where('group', $group);
    }
    $result = $this->db->where('hash', $hash)->get('project')->row();
    if(!empty($result)) {
      if($result->hide) return false;
      return $result;
    }
    return false;
  }

  function delete($hash) {
    return $this->db->query('UPDATE project SET hide=1 WHERE hash='.$hash);
  }

  function getAll($group) {
    if($group == 'admin') return $this->db->get('project')->result();
    return $this->db->where('group', $group)->get('project')->result();
  }

  function edit($hash, $name, $summary, $tagColor, $group) {
    $this->db->where('hash', $hash)->update('project', array(
      'name' => $name,
      'summary' => $summary,
      'tagColor' => $tagColor,
      'group' => $group
    ));
    return $this->get($hash);
  }
}
